let source = null;
let outBox = document.querySelector(".box");
let target = null;
document.querySelector(".box").addEventListener("dragstart", (e) => {
  source = e.target;
  e.dataTransfer.effectAllowed = "move";
  const itemList = Array.from(outBox.children);
  itemList.forEach((item, index) => {
    item.dataset.index = index;
    item.style.transform = "translateY(0)";
  });
  setTimeout(() => e.target.classList.add("draggable"), 0);
});
document.querySelector(".box").addEventListener("dragenter", (e) => {
  if (e.target == outBox || e.target == source) return;
  target = e.target;
  const itemList = Array.from(outBox.children);
  const targetIndex = itemList.indexOf(target);
  const sourceIndex = itemList.indexOf(source);
  if (targetIndex > sourceIndex) {
    outBox.insertBefore(target, source);
  } else {
    outBox.insertBefore(source, target);
  }
  const updatedItemList = Array.from(outBox.children);
  // updatedItemList.forEach((item, itemIndex) => {
  //   if (targetIndex > sourceIndex) {
  //     console.log('向上');
  //     if (itemIndex > sourceIndex && itemIndex <= targetIndex && item !== source) {
  //       item.style.transform = `translateY(${-108 / 2}px)`; // 高度+间距
  //     }
  //   } else {
  //     // 向下移动情况
  //     console.log('向下');
  //     if (itemIndex < sourceIndex && itemIndex >= targetIndex && item !== source) {
  //       item.style.transform = `translateY(${108 / 2}px)`; // 高度+间距;
  //     }
  //   }
  // })
});
document.querySelector(".box").addEventListener("dragend", (e) => {
  const itemList = Array.from(outBox.children);
  // const targetIndex = itemList.indexOf(target)
  // const sourceIndex = itemList.indexOf(source)
  // if (targetIndex > sourceIndex) {
  //   outBox.insertBefore(source, itemList[targetIndex + 1] || null);
  // } else {
  //   outBox.insertBefore(source, target);
  // }
  e.target.classList.remove("draggable");
  itemList.forEach((item, index) => {
    item.style.transform = "";
  });
  source = null;
  target = null;
});
document.querySelector(".box").addEventListener("dragover", (e) => {
  e.preventDefault();
  e.dataTransfer.dropEffect = "move";
});
